package com.luxx.model;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.sql.Connection;
import java.util.Map;

import com.luxx.util.DBUtil;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class AbstractEngine {

	protected static Connection con;

	protected static Configuration cfg;

	public AbstractEngine(String templatePath) throws Exception {
		con = DBUtil.getConnection();
		try {
			cfg = new Configuration();
			cfg.setDefaultEncoding("utf-8");
			cfg.setDirectoryForTemplateLoading(new File(templatePath));
			cfg.setObjectWrapper(new DefaultObjectWrapper());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void create(String ftlTemplate, Map contents, String savePath, String saveFilename) {
		try {
			Template temp = cfg.getTemplate(ftlTemplate);
			File file = new File(savePath);
			if (!file.exists()) {
				file.mkdirs();
			}
			Writer out = new OutputStreamWriter(new FileOutputStream(savePath + "/" + saveFilename), "utf-8");
			temp.process(contents, out);
			out.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (TemplateException e1) {
			e1.printStackTrace();
		}
	}
}
